package com.fruit.controller;


import cn.hutool.json.JSONUtil;
import com.fruit.ProductInfoOutPut;
import com.fruit.dao.ProductDao;
import com.fruit.model.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: LJ
 * @Date: 2018/10/25 11:44
 * @version:
 */
@RestController
@Slf4j
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductDao productDao;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @GetMapping("list")
    public  List<ProductInfo>  list(HttpServletRequest request){
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("cookie={}",request.getCookies());
        List<ProductInfo> products = productDao.findAll();
        log.info("products={}",products);
        return products;
    }
    @GetMapping("/listForOder")
    public  List<ProductInfoOutPut>  listForOder(){
        List<ProductInfoOutPut> products = productDao.findAll().stream().map(e -> {
            ProductInfoOutPut output = new ProductInfoOutPut();
            BeanUtils.copyProperties(e, output);
            return output;
        }).collect(Collectors.toList());
        log.info("result={}",products);
        //发送mq消息（json转字符串）
        String message = JSONUtil.toJsonStr(products.get(0));

        amqpTemplate.convertAndSend("productInfo",message);
        return products;
    }
}
